import axios from "axios";
import { ElMessage } from "element-plus";
import router from "../router/router";
const service = axios.create({
  baseURL: "/api",
});

// Request interceptors
service.interceptors.request.use(
  (config) => {
    if (localStorage.getItem("token"))
      config.headers.token = localStorage.getItem("token");

    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// Response interceptors
service.interceptors.response.use(
  (response) => {
    if (response.data.code === 500) {
      router.push("/500");
      return;
    } else if (response.data.code === 401) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
      router.push("/login");
      localStorage.removeItem("token");
      ;
      sessionStorage.removeItem("commonUse");
      sessionStorage.removeItem("UserInfo");
    } else if (response.data.code !== 200) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
      return;
    }
    return response;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);

export default service;
